﻿package 
{
	import br.com.stimuli.loading.BulkLoader;
	import br.com.stimuli.loading.BulkProgressEvent;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
		import flash.net.*;
		

	import flash.events.*;
	import flash.filters.GlowFilter;
	import gs.easing.Quint;
	import gs.TweenLite;
	import org.papervision3d.events.InteractiveScene3DEvent;
	import org.papervision3d.materials.BitmapMaterial;
	import org.papervision3d.objects.DisplayObject3D;
	import org.papervision3d.objects.primitives.Plane;
	import org.papervision3d.view.BasicView;
	import flash.text.*;
	import flash.display.*;
	//import flash.display.MovieClip;
	
	import flash.external.ExternalInterface;

	/**
	 * ...
	 * @author Charlie Schulze, charlie[at]woveninteractive[dot]com
	 * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
	 */
 
	public class Main extends BasicView 
	{
		protected var planes:Array = [];
		protected var images:Array = [];
		protected var pageUrls:Array = [];
		protected var displayNames:Array = [];
		protected var numItems:Number;
		protected var currentItem:Number;
		protected var oldItem:int;
		protected var angle:Number = 25;		
		protected var rightBtn:Sprite;
		protected var leftBtn:Sprite;
		protected var PlaneClick:Boolean;
		
		protected var xmlPath:String;// = "http://localhost/Schiebel/Press-Area/Videos.aspx?AcmsTF=FlashXml";
		//protected var xmlPath : URLRequest = new URLRequest("http://localhost/Schiebel/VideoCarousel.xml");
		private var tf:TextField = new TextField(); 
		
		protected var bulkInstance:BulkLoader;
 
		public function Main():void 
		{
			var arialfont:Font = new Arial;
			
			var ArialFormat:TextFormat = new TextFormat();
				ArialFormat.size = 11;
				ArialFormat.align = TextFormatAlign.LEFT;
				ArialFormat.color = 0x000000;
				ArialFormat.font = arialfont.fontName;
			
			tf.x = (stage.stageWidth/2)-(tf.width /2);
			tf.y = 300;
			tf.text = "here";
			tf.autoSize = TextFieldAutoSize.LEFT;
			tf.border = false;
			tf.textColor = 0xFF0000;
			tf.defaultTextFormat = ArialFormat;
			tf.embedFonts = true;
			tf.antiAliasType = AntiAliasType.ADVANCED;
			addChild(tf);
			
			var keyStr:String;
			var valueStr:String;
			var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
			//load Flash Vars
			try {
			   // var keyStr:String;
			  //  var valueStr:String;
			   // var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
			    //var build:String="x";
				for (keyStr in paramObj) {
			        valueStr = String(paramObj[keyStr]);
			        //tf.appendText("\t"+ valueStr "\n");
					
					if(keyStr=="SettingsFilePath"){
						xmlPath=valueStr+"";
						//build=valueStr;
						//tf.appendText("build1:["+build+"]");
					}
				}
			} catch (error:Error) {
				    tf.appendText(error.toString());
			}
			if(xmlPath!=null){
				if (xmlPath.search("AcmsTF=FlashXml") == -1) {
					xmlPath = xmlPath + "&AcmsTF=FlashXml";
				}
			}
			else {
				xmlPath = "http://www.schiebel.net/Press-Area/Videos.aspx?AcmsTF=FlashXml&fail";
				}
			var xmlUrlloader:URLLoader = new URLLoader();
            configureXMLListeners(xmlUrlloader);
			 
			
			var xmlURLRequest:URLRequest = new URLRequest(xmlPath);
			//var xmlURLRequest:URLRequest = new URLRequest("http://localhost/Schiebel/Press-Area/Videos.aspx?AcmsTF=FlashXml");
			//var xmlURLRequest:URLRequest = new URLRequest("xxhttp://localhost/Parlourwood/default.aspx?AcmsSV=Pending&AcmsTF=FlashXml");
			//var xmlURLRequest:URLRequest = new URLRequest("xxhttp://localhost/Parlourwood/default.aspx?AcmsSV=Pending&AcmsTF=FlashXml");
			xmlUrlloader.load(xmlURLRequest);
			
			//xmlPath = "http://localhost/Schiebel/Press-Area/Videos.aspx?AcmsTF=FlashXml";
			//xmlPath = "http://localhost/Schiebel/Press-Area/Videos.aspx?AcmsSV=Pending&AcmsTF=FlashXml";
			
			//Make sure that your scene is set to interactive
			super(960, 362, true, true);
			//loadXML();
			
		}
		
		private function configureXMLListeners(dispatcher:IEventDispatcher):void {
            dispatcher.addEventListener(Event.COMPLETE, xmlCompleteHandler);
            //dispatcher.addEventListener(ProgressEvent.PROGRESS, xmlProgressHandler);
			//dispatcher.addEventListener(IOErrorEvent.IO_ERROR, xmlIoErrorHandler);
        }

		//First load our XML
		protected function loadXML():void 
		{
			//tf.text = "load:"+xmlPath;
			//bulkInstance = new BulkLoader("bulkInstance");			
			//bulkInstance.add(xmlPath, {type:"xml"});
			//bulkInstance.addEventListener(BulkProgressEvent.COMPLETE, onXMLReady);
			//bulkInstance.start();
		}
 
		//When our xml is ready parse and load our images
		 protected function xmlCompleteHandler(event:Event):void {
			 
			 tf.text="ready";
			bulkInstance = new BulkLoader("bulkInstance");
			 //bulkInstance.removeEventListener(BulkProgressEvent.COMPLETE, onXMLReady);
			tf.text = event.target + "";
			var urlloaderb:URLLoader = URLLoader(event.target);
            //trace("completeHandler: " + urlloaderb.data);
			//var xml:XML = 
			
			bulkInstance.addEventListener(BulkProgressEvent.COMPLETE, onImagesReady);
			bulkInstance.start();
			var xml:XML = new XML(urlloaderb.data);
			var xmlList:XMLList = xml.image;
 
			for (var i:int = 0; i < xmlList.length(); i++) 
			{
				var imagePath:String = String(xmlList[i])
				tf.text = imagePath;
				trace(imagePath);
				bulkInstance.add(imagePath);
 				//Add path to array for later access
				images.push(imagePath);
			}
			
			var xmlListpageUrl:XMLList = xml.pageUrl;
			for (var p:int = 0; p < xmlListpageUrl.length(); p++) 
			{	
				tf.text = "Get Image Urls";
				var pagePath:String = String(xmlListpageUrl[p])
				tf.text = pagePath;
				trace(pagePath);
				//bulkInstance.add(pagePath);
 				//Add path to array for later access
				pageUrls.push(pagePath);
			}
			
			var xmlListdisplayName:XMLList = xml.displayName;
			for (var d:int = 0; d < xmlListdisplayName.length(); d++) 
			{	
				var displayName:String = String(xmlListdisplayName[d])
				tf.text = displayName;
				//trace(pagePath);
				//bulkInstance.add(pagePath);
 				//Add path to array for later access
				displayNames.push(displayName);
				trace(d + "." + displayName+"."+displayNames[d]);
				
				
				
			}
 
			//Set our number of items based on how many images we load
			numItems = images.length;
			currentItem = Math.round(images.length/2);
			//trace(currentItem);
		}
 
		//Images are finished loading we can now create our papervision coverflow
		protected function onImagesReady(evt:BulkProgressEvent):void 
		{
			init();
		}
 
		protected function init():void 
		{
			createChildren();
			createNavigation();
			animate();
			startRendering();
		}
		
		protected function createChildren():void 
		{
			for (var i:int = 0; i < numItems; i++) 
			{
				//Grab our bitmapData from the bulkLoader using our array of image paths as our key
				var mat:BitmapMaterial 	= new BitmapMaterial(bulkInstance.getBitmapData(images[i]));
				mat.interactive 		= true;
				mat.smooth 				= true;
				var plane:Plane 		= new Plane(mat, 305, 212, 4, 4);
				
 
				planes.push(plane);
 
				//Click straight to any plane
				plane.addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, onPlaneClick);
				
				plane.addEventListener( InteractiveScene3DEvent.OBJECT_OVER, onPlaneOver ); // Will trigger "onOver" when the mouse rolls over the object
				plane.addEventListener( InteractiveScene3DEvent.OBJECT_OUT, onPlaneOut ); // Will trigger "onOut" when the mouse rolls out of the object

 
				//Set an id to target current item
				plane.id = i;
 
				//Add plane to the scene
				scene.addChild(plane);
			}
 			camera.zoom = 70;
		}
 
		protected function onPlaneClick(evt:InteractiveScene3DEvent):void 
		{
			//ExternalInterface.call("launchtb()");
			//tf.text = "click";
			//tf.text = "click";
			oldItem = currentItem;
			currentItem = evt.target.id;
			PlaneClick = true;
			animate();
		}
		
		protected function onPlaneOver (evt:InteractiveScene3DEvent):void 
		{
			//Mouse.hide();
			viewport.buttonMode = true;
			//flash.ui.Mouse.cursor = "button";
			//flash.ui.MouseCursor.HAND;
			//this.useHandCursor = true;
		}
		protected function onPlaneOut (evt:InteractiveScene3DEvent):void 
		{
			viewport.buttonMode = true;
			//Mouse.show();
			//flash.ui.MouseCursor.ARROW;
			//flash.ui.Mouse.cursor="auto"
			//this.useHandCursor = false;
			//flash.ui.Mouse.show;// cursor = "auto";
		}
 
		//Animate the coverflow left / right based off of currentItems
		protected function animate():void 
		{
			if (currentItem == oldItem && PlaneClick == true ) {
				if (ExternalInterface.available) {
					tf.text= "ei available.";
					ExternalInterface.call("addFlashVideoSend", currentItem);
					//ExternalInterface.call("addFlashVideo", currentItem);
				}
			}
			
			if (ExternalInterface.available) {
					tf.text= "ei available.";
					ExternalInterface.call("toggleVideoItemInfo", currentItem);
				}
				
			if(displayNames[currentItem]!=null){
				tf.text = displayNames[currentItem];
			}
			else
			{
				tf.text = "Select A Video";
			}
			tf.x = (stage.stageWidth/2)-(tf.width /2);
			trace(displayNames[currentItem]);

			for (var i:int = 0; i < planes.length; i++) 
			{
				var plane:Plane = planes[i];
				
				//Each if statement will adjust these numbers as needed
				
				var planeX:Number = 0;
				var planeZ:Number = -50;
				var planeRotationY:Number = 0
 
				//Place  & Animate Center Item
				if (i == currentItem) 
				{
					planeZ 				= -300
 
					TweenLite.to(plane, 1, { rotationY:planeRotationY,x:planeX,z:planeZ, ease:Quint.easeInOut } );
				} 
 
				//Place & Animate Right Items
				if(i > currentItem)  
				{
					planeX 				= (i - currentItem + 1) * 120;
					planeRotationY 		= angle + 10 * (i - currentItem);
 
					TweenLite.to(plane, 1, { rotationY:planeRotationY,x:planeX,z:planeZ, ease:Quint.easeInOut } );
				}
 
				//Place & Animate Left Items
				if (i < currentItem) 
				{
					planeX 				= (currentItem - i + 1) * -120;
					planeRotationY 		= -angle - 10 * (currentItem - i);
 
					TweenLite.to(plane, 1, { rotationY:planeRotationY,x:planeX,z:planeZ, ease:Quint.easeInOut } );
				}
			}
		}
 
		/*
		 * Everything below this point is just for creating the buttons and
		 * setting button events for controlling the coverflow. 
		 */
 
		protected function createNavigation():void 
		{
			//Create / Add Buttons
			rightBtn = createButton();
			leftBtn = createButton();
 
			addChild(leftBtn);
			addChild(rightBtn);
 
			//Add button listeners
			rightBtn.buttonMode = true;
			leftBtn.buttonMode = true;
			rightBtn.addEventListener(MouseEvent.CLICK, buttonClick);
			leftBtn.addEventListener(MouseEvent.CLICK, buttonClick);
 
			//Place buttons on stage
			rightBtn.x 			= stage.stageWidth - 20;
			leftBtn.x 			= 20;
			rightBtn.y 			=  stage.stageHeight / 2;
			leftBtn.y 			=  (stage.stageHeight / 2) + 20;
			leftBtn.rotation 	= 180;
		}
 
		//Button actions
		protected function buttonClick(evt:MouseEvent):void 
		{
			PlaneClick = false;
			switch (evt.target)
			{
				case rightBtn:
				currentItem ++
				break;
 
				case leftBtn:
				currentItem --;
				break;
			}
 
			//Don't allow any number lower than 0 or past max so there
			//is always a center item
 
			if (currentItem < 0)
			{
				currentItem = 0;
			}
			if (currentItem > (planes.length - 1))
			{
				currentItem = planes.length - 1;
			}
 
			//Call animation
			animate();
		}
 
		//Creates a simple arrow shape / returns the sprite
		protected function createButton():Sprite
		{
			var btn:Sprite = new Sprite();
 
			btn.graphics.beginFill(0x333333);
			btn.graphics.moveTo(0, 0);
			btn.graphics.lineTo(0, 10);
			btn.graphics.lineTo(5, 5);
			btn.graphics.lineTo(0, 0);
			btn.graphics.endFill();
			//btn.filters = [new GlowFilter(0xFFFFFF,1,10,10,3)]
			return btn;
		}
				
		//js call
	}
}
